//index.js
//获取应用实例
const app = getApp()
const nt_util = require('../../utils/nt_util.js')

Page({
  data: {
    items:{},
    userInfo: {}
  },

  diancan: function () {
    wx.navigateTo({
      url: '../order/dinnertype'
    })
  },

  pay: function () {
    wx.navigateTo({
      url: '../pay/pay'
    })
  },

  onLoad: function () {
     this.bindBuyer()
  },
  bindBuyer:function(){
    let that = this
    // 如果本地没有绑定手机号
    if (!nt_util.getMobile()) {
      //登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          nt_util.httpRequest(nt_util.api.bindBuyer, 'post', {
            code: res.code
          }, function (data) {
            let _openId = '';
            _openId = data.data.buyer.openid;
            wx.setStorage({
              key: "openId",
              data: _openId
            })

            wx.setStorage({
              key: "mobile",
              data: data.data.buyer.mobile || ''
            })

            wx.setStorage({
              key: "buyerId",
              data: data.data.buyer.id || ''
            })

            // 获取用户状态
            that.checkBuyerStatus()

          });
        }
      })
    }
  },
  getBuyerOrders: function () {
    let buyerId = nt_util.getBuyerId();
    nt_util.httpRequest(nt_util.api.getBuyerOrders, 'get', {
      buyerId: buyerId,
      type:0
    }, function (data) {
      nt_util.that.setData({
        items: data.data.orderList || []
      });
    });
  },
  tapItem: function (event) {
    var dataset = event.currentTarget.dataset;
    var index = dataset.index
    var _queryObj = this.data.items[index];
    var queryObj = {
      orderId: _queryObj.orderId,
      qrcode: _queryObj.qrcode
    }
    //将对象转为string
    var queryBean = JSON.stringify(queryObj)
    var url = '/pages/fanpiao/fanpiao?queryBean=' + queryBean;
    wx.navigateTo({
      url: url
    })
  },
  onShow: function () {
    nt_util.that = this;
    this.getBuyerOrders();
    this.checkBuyerStatus()
  },

  checkBuyerStatus:function(){
    if (!nt_util.getOpenId()) return;
    let that = this
    // 获取用户状态
    nt_util.httpRequest(nt_util.api.checkBuyerStatus, 'get', {
      openId: nt_util.getOpenId()
    }, function (data) {
      nt_util.log(data)
      if (data.code == -1) {
        wx.redirectTo({
          url: '/pages/login/login',
        })
      } else {
        that.setData({
          userInfo: data.data.buyer
        })
      }
    });
  }
})






